<template>
  <div>
    <el-dialog
      title="设置看板内容"
      :visible.sync="dialogVisible"
      :modal="true"
      :appendToBody="true"
      width="600px"
      v-dialog-drag
      :close-on-click-modal="false"
      top="5vh"
      @close="handleClose()"
      @open="handleOpen()"
    >
      <el-form
        :model="form"
        :rules="rules"
        ref="ruleForm"
        label-width="120px"
        v-loading="loading"
      >
        <el-form-item label="看板展示区域" prop="taskBoardName">
          <span>{{ form.taskBoardName }}</span>
        </el-form-item>
        <el-form-item label="关联工序" prop="workSectionCode">
          <el-select
            v-model="form.workSectionCode"
            filterable
            clearable
            multiple
            placeholder="请选择关联工序"
          >
            <el-option
              v-for="item in workSectionOptions"
              :key="item.workSectionCode"
              :label="item.workSectionName"
              :value="item.workSectionCode"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="关联任务模板" prop="taskTemplateCode">
          <el-select
            v-model="form.taskTemplateCode"
            filterable
            clearable
            placeholder="请选择关联任务模板"
            @change="handleTaskTemplateChange"
          >
            <el-option
              v-for="item in taskTemplateOptions"
              :key="item.taskTemplateCode"
              :label="item.taskTemplateName"
              :value="item.taskTemplateCode"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="展示内容" prop="titleList">
          <el-button type="text" @click="openField">选择字段</el-button>
          <span class="tip">（最多5个）</span>
          <el-row v-for="(item, i) in form.titleList" :key="i">
            <el-col :span="14">
              {{ item.label }}
            </el-col>
            <el-col :span="10">
              <el-button
                v-if="item.boardColIndex != 1"
                type="text"
                @click="handleUp(item)"
                >上移</el-button
              >
              <el-button
                v-if="item.boardColIndex != form.titleList.length"
                type="text"
                @click="handleDown(item)"
                >下移</el-button
              >
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" :loading="saveloading" @click="handleSubmit"
          >确 定</el-button
        >
      </span>
    </el-dialog>

    <FieldDialog
      :visible.sync="fieldDialog.visible"
      :taskTemplateCode="form.taskTemplateCode"
      @submit="closeField"
    ></FieldDialog>
  </div>
</template>
<script>
import { getTaskTemplateList } from "@/api/taskMgmt/template";
import { listWorkSection } from "@/api/workMgmt/workSection";
import FieldDialog from "./fieldDialog";
import { saveKanbanInfo } from "@/api/taskMgmt/kanbanConfig";
export default {
  components: { FieldDialog },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    row: {
      type: Object,
      default: null,
    },
  },
  data() {
    return {
      form: {
        id: null,
        taskBoardName: "",
        workSectionCode: [],
        taskTemplateCode: "",
        titleList: [],
      },
      rules: {},
      workSectionOptions: [],
      taskTemplateOptions: [],
      fieldDialog: {
        visible: false,
      },
      loading: false,
      saveloading: false,
    };
  },
  computed: {
    dialogVisible: {
      set(val) {
        this.$emit("update:visible", val);
      },
      get() {
        return this.visible;
      },
    },
  },
  methods: {
    handleClose() {
      this.form = {
        id: null,
        taskBoardName: "",
        workSectionCode: [],
        taskTemplateCode: "",
        titleList: [],
      };
      this.$refs.ruleForm.resetFields();
    },
    handleOpen() {
      this.getWorkSectionOptions();
      this.getTaskTemplateOptions();

      if (this.row) {
        const {
          id,
          taskBoardName,
          workSectionCode,
          taskTemplateCode,
          boardFieldList,
        } = this.row;
        // 排序
        let _boardFieldList = [];
        if (boardFieldList) {
          _boardFieldList = boardFieldList.sort((a, b) => {
            return a.boardColIndex > b.boardColIndex ? 1 : -1;
          });
        }
        this.form = {
          id,
          taskBoardName,
          workSectionCode: workSectionCode ? workSectionCode.split(",") : [],
          taskTemplateCode,
          titleList: _boardFieldList
            ? _boardFieldList.map((ele, i) => ({
                id: ele.id,
                label: ele.label,
                boardColIndex: i + 1,
              }))
            : [],
        };
      }
    },
    // 获取工序列表
    getWorkSectionOptions() {
      const param = {
        query: {
          searchValue: "",
        },
        pageNum: 1,
        pageSize: 2000,
      };
      listWorkSection(param)
        .then((res) => {
          let workSectionOptions = res?.rows || [];

          // 名称升序排序
          workSectionOptions = workSectionOptions.sort((a, b) => {
            return a.workSectionName && b.workSectionName
              ? a.workSectionName.localeCompare(b.workSectionName)
              : -1;
          });

          this.workSectionOptions = workSectionOptions;
        })
        .catch(() => {
          this.workSectionOptions = [];
        });
    },
    // 获取任务模板列表
    getTaskTemplateOptions() {
      const param = {
        pageNum: 1,
        pageSize: 2000,
        query: {
          templateName: "",
          taskType: "",
          status: "1", //启用的
          templateCategory: "custom",
        },
      };
      getTaskTemplateList(param)
        .then((res) => {
          this.taskTemplateOptions = res.rows || [];
        })
        .catch(() => {
          this.list = [];
        });
    },
    openField() {
      if (!this.form.taskTemplateCode) {
        this.msgWarning("请先选择关联任务模板！");
        return;
      }
      this.fieldDialog.visible = true;
    },
    closeField(list) {
      if (!list?.length) {
        this.form.titleList = [];
      } else {
        this.form.titleList = list.map((ele, index) => ({
          id: ele.id,
          label: ele.label,
          boardColIndex: index + 1,
        }));
      }
    },
    handleUp(item) {
      const index = this.form.titleList.findIndex((ele) => ele.id == item.id);
      if (this.form.titleList[index].boardColIndex > 1) {
        this.form.titleList[index].boardColIndex -= 1;
        this.form.titleList[index - 1].boardColIndex += 1;
        this.form.titleList.sort((a, b) => {
          return a.boardColIndex > b.boardColIndex ? 1 : -1;
        });
      }
    },
    handleDown(item) {
      const index = this.form.titleList.findIndex((ele) => ele.id == item.id);
      if (
        this.form.titleList[index].boardColIndex < this.form.titleList.length
      ) {
        this.form.titleList[index].boardColIndex += 1;
        this.form.titleList[index + 1].boardColIndex -= 1;
        this.form.titleList.sort((a, b) => {
          return a.boardColIndex > b.boardColIndex ? 1 : -1;
        });
      }
    },
    handleTaskTemplateChange(value) {
      // 清空
      this.form.titleList = [];
    },
    handleSubmit() {
      const { id } = this.row;
      const { workSectionCode, taskTemplateCode, titleList } = this.form;
      const param = {
        taskBoardId: id,
        workSectionCode: workSectionCode ? workSectionCode.join(",") : "",
        taskTemplateCode,
        boardInfo: titleList.map((ele) => ({
          id: ele.id,
          boardColIndex: ele.boardColIndex,
        })),
      };
      this.saveloading = true;
      saveKanbanInfo(param)
        .then((res) => {
          if (res.code == 200) {
            this.msgSuccess("保存成功!");
            this.$emit("refresh");
            this.dialogVisible = false;
          }
        })
        .catch(() => {})
        .finally(() => {
          this.saveloading = false;
        });
    },
  },
};
</script>
<style lang="scss" scoped>
.tip {
  color: #cccccc;
}
.el-form {
  .el-select {
    width: 70%;
  }
}
</style>
